/**
 * 
 */
package br.odb.bzk3.android;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Looper;
import android.util.Log;

/**
 * @author monty
 *
 */
public class EngineActivity extends Activity implements Runnable {
	public static int selected;
	InputStream data;
	static ProgressDialog myProgressDialog;
	static EngineView engineView;
	

	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myProgressDialog = ProgressDialog.show( this, "loading", "Loading level data" );
		
		
		engineView = new EngineView( this );		
		Thread t = new Thread( this );
		t.start();
		
		
//		data = file( selected );
//		engineView = new EngineView( this );
//		engineView.load( data );
//		engineView.loadComplete();
//		setContentView( engineView );
		
		
	}
	
	private InputStream file(int lvl) {
		InputStream is = null;
		switch (lvl) {
		case 0:
			is = getResources().openRawResource(R.raw.prison );
			break;
		case 1:
			is = getResources().openRawResource(R.raw.geo );
			break;
		case 2:
			is = getResources().openRawResource(R.raw.level_1_3);
			break;
		case 3:
			is = getResources().openRawResource(R.raw.level_1_4);
			break;
		case 4:
			is = getResources().openRawResource(R.raw.level_2_1);
			break;

		case 5:
			is = getResources().openRawResource(R.raw.level_2_2);
			break;

		case 6:
			is = getResources().openRawResource(R.raw.level_2_3);
			break;

		case 7:
			is = getResources().openRawResource(R.raw.level_2_4);
			break;
		case 8:
			is = getResources().openRawResource(R.raw.level_2_5);
			break;

		}
		Log.d("Willie","Abastecendo buffer");
		 StringBuffer sb = new StringBuffer();
		 String tmp = "";
		 try
		 {
		 int chars;
		 while ((chars = is.read()) != -1)
		 {
		 sb.append((char) chars);
		 }
		 tmp = sb.toString();
		 } catch (Exception e)
		 {
		 }
		Log.d("Willie","Abastecendo buffer");
		return new ByteArrayInputStream( tmp.getBytes() );
	}
	
	private class Runnable2 implements Runnable {
		private Activity activity;
				
	@Override
		public void run() {
			myProgressDialog.dismiss();
			setContentView( engineView );
		}	
	}	
	
	@Override
	public void run() {
		Looper.myLooper().prepare();
		Log.d("Willie","preparando leitura");
		data = file( selected );
		Log.d("Willie","buffer criado");
		long m0 = System.currentTimeMillis();
		engineView.load( data );
		engineView.loadComplete();
		long m1 = System.currentTimeMillis();
		System.out.println( "delta: " + ( m1 - m0 ) );
		
		runOnUiThread( new Runnable2( ) );
	}
}
